<template>
  <div class="space-y" style="padding-bottom: 80px;">
    <div v-if="restaurant">
      <h2>{{ restaurant.name }}</h2>
      <div class="muted">{{ restaurant.address }} · {{ restaurant.phone }}</div>
    </div>
    <div class="search-bar" style="max-width:520px;">
      <input class="input" v-model="keyword" placeholder="搜索菜品名称..." @keyup.enter="loadMenu" />
      <button class="btn" @click="loadMenu">搜索</button>
      <button class="btn ghost" @click="clearSearch">清空</button>
    </div>
    <h3 style="margin-top:16px;">菜单</h3>
    <div class="card" v-for="m in menu" :key="m.id" style="padding:10px;display:flex;gap:12px;align-items:center;">
      <img :src="m.imageUrl" style="width:96px;height:72px;object-fit:cover;" class="rounded" />
      <div style="flex:1;">
        <div style="font-weight:700;">{{ m.name }} <span class="muted" style="font-weight:400;">{{ m.category }}</span></div>
        <div class="muted" style="font-size:12px;">{{ m.description }}</div>
      </div>
      <div class="price">¥ {{ m.price }}</div>
      <div style="display:flex;align-items:center;gap:10px;">
        <span v-if="getItemQuantity(m.id) > 0" class="badge" style="background-color:#3b82f6;">{{ getItemQuantity(m.id) }}</span>
        <button class="btn" @click="addToCart(m)">加入购物车</button>
        <button v-if="getItemQuantity(m.id) > 0" class="btn ghost" style="color:#ef4444;" @click="removeFromCart(m.id)">-</button>
      </div>
    </div>
  </div>
  
  <!-- 固定在屏幕底部的购物车框 -->
  <div v-if="cartItems.length > 0" class="card" style="position: fixed; bottom: 0; left: 0; right: 0; padding: 16px; z-index: 100; background-color: rgba(255, 255, 255, 0.95); border-top: 1px solid #e5e7eb; box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);">
    <div class="row" style="justify-content:space-between; align-items:center;">
      <div>购物车中有 {{ cartTotalItems }} 件商品</div>
      <a class="btn primary" href="#/cart" style="padding: 8px 24px;">去购物车结算</a>
    </div>
  </div>
</template>

<script>
export default {
  data(){ return { id: null, restaurant:null, menu: [], keyword:'', cartItems: [] } },
  async created(){
    const parts = (location.hash||'').split('/')
    this.id = parts[2]
    const rRes = await fetch(`/api/v1/restaurants/${this.id}`)
    this.restaurant = await rRes.json()
    await this.loadMenu()
    this.updateCartItems()
    window.addEventListener('storage', this.handleStorageChange)
  },
  beforeUnmount(){
    window.removeEventListener('storage', this.handleStorageChange)
  },
  computed: {
    cartTotalItems() {
      return this.cartItems.reduce((total, item) => total + item.quantity, 0)
    }
  },
  methods:{
    async loadMenu(){
      const q = this.keyword && this.keyword.trim() ? `?q=${encodeURIComponent(this.keyword.trim())}` : ''
      const res = await fetch(`/api/v1/restaurants/${this.id}/menu${q}`)
      this.menu = await res.json()
    },
    clearSearch(){ this.keyword=''; this.loadMenu() },
    addToCart(item){
      // 检查用户是否登录
      const user = JSON.parse(localStorage.getItem('user') || 'null')
      if (!user) {
        alert('请先登录后再添加商品到购物车')
        location.hash = '#/login'
        return
      }
      
      const cart = JSON.parse(localStorage.getItem('cart')||'[]')
      const found = cart.find(c=>c.menuItemId===item.id)
      if(found){
        found.quantity+=1
        localStorage.setItem('cart', JSON.stringify(cart))
        this.updateCartItems()
      }
      else {
        cart.push({ menuItemId:item.id, name:item.name, price:item.price, quantity:1, restaurantId:item.restaurantId || this.id })
        localStorage.setItem('cart', JSON.stringify(cart))
        this.updateCartItems()
      }
      // 触发storage事件以便多标签页同步
      window.dispatchEvent(new Event('storage'))
    },
    updateCartItems(){
      this.cartItems = JSON.parse(localStorage.getItem('cart')||'[]')
    },
    getItemQuantity(menuItemId){
      const item = this.cartItems.find(c => c.menuItemId === menuItemId)
      return item ? item.quantity : 0
    },
    handleStorageChange(){
      this.updateCartItems()
    },
    removeFromCart(menuItemId) {
      const cart = JSON.parse(localStorage.getItem('cart')||'[]')
      const index = cart.findIndex(c => c.menuItemId === menuItemId)
      if(index !== -1) {
        if(cart[index].quantity > 1) {
          // 如果商品数量大于1，则减少1个
          cart[index].quantity--
        } else {
          // 如果商品数量等于1，则从购物车中完全移除
          cart.splice(index, 1)
        }
        localStorage.setItem('cart', JSON.stringify(cart))
        this.updateCartItems()
        // 触发storage事件以便多标签页同步
        window.dispatchEvent(new Event('storage'))
      }
    }
  }
}
</script>


